<template>
    <el-form class="form" :model="form" :rules="rules" ref="form">
        <h3 class="form_title">发表新攻略</h3>
        <p class="form_info">分享你的个人游记，让更多人看到哦！</p>
        <el-form-item prop="title">
            <el-input placeholder="请输入标题" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item prop="content">
            <editor
                id="textarea"
                api-key="qqpgs076xviy5x4asa1c3grdpzntfzb2hcazvidpkrrj8hf1"
                :init="init"
                v-model="form.content"
            />
        </el-form-item>
        <el-form-item label="选择城市" prop="city">
            <el-autocomplete
                v-model="form.city"
                style="width: 150px"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearchAsync"
                placeholder="请选择游玩城市"
            ></el-autocomplete>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" size="mini" @click="sendPost">发布</el-button>&nbsp;&nbsp; 或者&nbsp;
            <a class="save_draft" @click="saveDraft">保存到草稿箱</a>
        </el-form-item>
    </el-form>
</template>

<script>
import Editor from "@tinymce/tinymce-vue";
export default {
    components: {
        editor: Editor,
    },
    props: ["draft"],
    watch: {
        draft() {
            this.form = this.draft;
        },
    },
    data() {
        return {
            // 富文本框配置项
            init: {
                height: 500,
                // 头部菜单不显示
                menubar: false,
                // 修改为中文
                language: "zh_CN",
                 paste_data_images: true,
                // 自动聚焦
                // auto_focus: 'textarea',
                images_upload_handler: this.images_upload_handler,
                plugins: [
                    "advlist autolink lists link image charmap print preview anchor",
                    "searchreplace visualblocks code fullscreen",
                    "insertdatetime media table paste code wordcount",
                ],
                toolbar:
                    "formatselect | bold italic table | \
                        alignleft aligncenter alignright alignjustify | \
                         numlist outdent indent  code image insertdatetime ",
            },
            form: {
                title: "",
                content: "",
                city: "",
            },
            // 校验规则对象
            rules: {
                title: [
                    {
                        required: true,
                        message: "请输入活动名称",
                        trigger: "blur",
                    },
                ],
                city: [
                    {
                        required: true,
                        message: "请输入活动名称",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    methods: {
        sendPost() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const { token } = this.$store.state.user;
                    // 判断是否有token
                    if (token) {
                        // 有token
                        if (!this.form.content) {
                            this.$message.error("内容不能为空");
                            return;
                        }
                        this.$axios
                            .post("/posts", this.form, {
                                headers: {
                                    Authorization: "Bearer " + token,
                                },
                            })
                            .then((res) => {
                                this.$message.success(res.data.message);
                            });
                    } else {
                        // 没有token
                        // 保存来源地址
                        this.$store.commit(
                            "page/setSourceURL",
                            this.$route.fullPath
                        );
                        this.$message.error("请先登陆");
                        // 跳转到登录页
                        setTimeout(() => {
                            this.$router.replace("/user/login");
                        }, 1000);
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        async querySearchAsync(querystr, cb) {
            let res = await this.$axios.get("/airs/city?name=" + querystr);
            const list = res.data.data.map((v) => ({ ...v, value: v.name }));
            cb(list);
        },
        // 保存到草稿箱
        saveDraft() {
            // 获取当前事件
            let date = new Date().toLocaleDateString();
            const draft = { form: JSON.parse(JSON.stringify(this.form)), date };
            this.$store.commit("draft/saveDraft", draft);
        },
        async images_upload_handler(blobInfo, success, fail) {
            const file = blobInfo.blob(); //转化为易于理解的file对象
            const fd = new FormData();
            fd.append("files", file);
            let res = await this.$axios.post("/upload", fd);
            console.log(res.data[0].url);
            success(this.$axios.defaults.baseURL + res.data[0].url);
        },
    },
};
</script>

<style lang="less" scoped>
.form {
    .form_title {
        font-weight: normal;
        font-size: 22px;
    }
    .form_info {
        font-size: 12px;
        color: #999;
        padding: 8px 0;
    }
    .save_draft {
        color: orange;
        cursor: pointer;
        &:hover {
            text-decoration: underline;
        }
    }
}
</style>
